package com.jackrain.clouddata.oms.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.clouddata.oms.util.KeyValueUtils;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.Set;

import static com.jackrain.clouddata.oms.util.KeyValueUtils.keyAppend;
import static com.jackrain.clouddata.oms.util.KeyValueUtils.valueAppend;

/**
 * Created by zcy on 2017/8/15.
 */
@Slf4j
@Component
public class ProDao {

    @Transactional
    public void execute(JSONObject mainJson, JSONArray itemArray, Long clientId) {
        log.info("====ProDao=======");
        String countSql = "SELECT COUNT(1) FROM C_PRO WHERE AD_CLIENT_ID = ? AND PROVALUE = ?";

        int count = QueryEngine.getInstance().doQueryInt(countSql, new Object[]{clientId, mainJson.getString("PROVALUE")});

        if (count == 0) {
            for (int i = 0; i < itemArray.size(); i++) {
                JSONObject itemJson = itemArray.getJSONObject(i);
                //获取字表名称
                String itemName = itemJson.getString("name");
                //获取value
                JSONArray paramList = null;
                JSONArray valueArray = itemJson.getJSONArray("value");
                if (valueArray != null && valueArray.size() > 0) {
                    JSONArray valuesA = new JSONArray();

                    for (int j = 0; j < valueArray.size(); j++) {
                        StringBuffer strItemBuf = new StringBuffer("INSERT INTO C_PROSKU (");
                        paramList = new JSONArray();
                        Set<String> itemKeySet = valueArray.getJSONObject(j).keySet();
                        for (String key : itemKeySet) {
                            strItemBuf.append(key + ",");
                            if (key.substring(key.length() - 4, key.length()).equals("DATE")) {
                                paramList.add(TypeUtils.castToDate(valueArray.getJSONObject(j).get(key)));
                            } else if (null == valueArray.getJSONObject(j).get(key) || "".equals(valueArray.getJSONObject(j).get(key))) {
                                paramList.add("");
                            } else {
                                paramList.add(valueArray.getJSONObject(j).get(key));
                            }
                        }
                        strItemBuf.append("ID,AD_CLIENT_ID) VALUES(");
                        for (int k = 0; k < itemKeySet.size(); k++) {
                            strItemBuf.append("?,");
                        }
                        strItemBuf.append("?,?)");
                        paramList.add(Tools.getSequence("C_PROSKU"));
                        paramList.add(clientId);
                        Integer insertprosku = QueryEngine.getInstance().executeUpdate(strItemBuf.toString(), paramList.toArray());
                        System.out.println(insertprosku + "****insertprosku**");
                    }
                }
            }

            JSONObject saleJson = JSON.parseObject(JSON.toJSONString(mainJson, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
            for (int i = 0; i < saleJson.keySet().size(); i++) {
                String key = (String) saleJson.keySet().toArray()[i];
                if (key.contains("DATE")) {
                    saleJson.put(key, TypeUtils.castToDate(mainJson.get(key)));
                }
            }
            saleJson.put("AD_CLIENT_ID", clientId);

            saleJson.put("ID", Tools.getSequence("C_PRO"));
            StringBuffer saleInsertSq = new StringBuffer();
            saleInsertSq.append("INSERT INTO C_PRO (" + keyAppend(saleJson.keySet()) + ") VALUES(").append(valueAppend(saleJson.size())).append(")");
            String saleInsertSql = saleInsertSq.toString();
            for (int j = 0; j < saleJson.keySet().size(); j++) {
                String key = (String) saleJson.keySet().toArray()[j];
                String value = saleJson.getString(key);
                if (value == null) {
                    if (!key.contains("DATE")) {
                        saleJson.put(key, "");
                    } else {
                        saleJson.remove(key);
                        saleInsertSql = saleInsertSql.replace(key + ",", "");
                    }
                }
            }
            QueryEngine.getInstance().executeUpdate(saleInsertSql.toString(), saleJson.values().toArray());
        } else {

            JSONObject proJson = JSON.parseObject(JSON.toJSONString(mainJson, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

            //调换SUPCODE位置
            proJson.remove("AD_CLIENT_ID");

            String provalues = (String) proJson.get("PROVALUE");
            proJson.remove("PROVALUE");


            String updateproSql = "UPDATE C_PRO SET " + KeyValueUtils.keyUpdateAppend(proJson.keySet()) + " WHERE AD_CLIENT_ID=? AND PROVALUE=?";
            proJson.put("AD_CLIENT_ID", clientId);
            proJson.put("PROVALUE", provalues);
            for (int j = 0; j < proJson.keySet().size(); j++) {
                String key = (String) proJson.keySet().toArray()[j];
                String value = proJson.getString(key);
                if (key.contains("DATE")) {
                    proJson.put(key, TypeUtils.castToDate(proJson.get(key)));
                }
                if (value == null) {
                    if (!key.contains("DATE")) {
                        proJson.put(key, "");
                    } else {
                        proJson.remove(key);
                        updateproSql = updateproSql.replace(key + "=?,", "");
                    }
                }
            }
            Integer resultcproupdate = QueryEngine.getInstance().executeUpdate(updateproSql, proJson.values().toArray());
//            System.out.println(resultcproupdate + "****resultcprouppdate**");

//            //生成updateSql语句

            if (resultcproupdate > 0) {
                for (int i = 0; i < itemArray.size(); i++) {
                    JSONObject itemskuJson = itemArray.getJSONObject(i);
                    //获取字表名称
                    String skuName = itemskuJson.getString("name");
                    //获取value

                    String updateskuSql = null;
                    JSONArray skuvalueArray = itemskuJson.getJSONArray("value");
                    if (skuvalueArray != null && skuvalueArray.size() > 0) {
//                      SKUNO
                        boolean updatesku = false;
                        JSONArray valuesAs = new JSONArray();

                        Integer ntims = 0;
                        boolean booleanpro = false;
                        for (int n = 0; n < skuvalueArray.size(); n++) {
                            JSONObject proskuJson = JSON.parseObject(JSON.toJSONString(skuvalueArray.getJSONObject(n), new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

                            proskuJson.remove("AD_CLIENT_ID");
//                            proskuJson.put("AD_CLIENT_ID", clientId);
                            String SKUNO = (String) proskuJson.get("SKUNO");
                            proskuJson.remove("SKUNO");
//                            proskuJson.put("PROVALUE", SKUNO);
                            //生成updateSql语句
//                                }
                            String skusb = "UPDATE C_PROSKU SET " + KeyValueUtils.keyUpdateAppend(proskuJson.keySet()) + " WHERE AD_CLIENT_ID=? AND SKUNO=?";
                            proskuJson.put("AD_CLIENT_ID", clientId);
                            proskuJson.put("SKUNO", SKUNO);
                            for (int h = 0; h < proskuJson.keySet().size(); h++) {
                                String key = (String) proskuJson.keySet().toArray()[h];
                                String value = proskuJson.getString(key);
                                if (key.contains("DATE")) {
                                    proskuJson.put(key, TypeUtils.castToDate(proskuJson.get(key)));
                                }
                                if (value == null) {
                                    if (!key.contains("DATE")) {
                                        proskuJson.put(key, "");
                                    } else {
                                        proskuJson.remove(key);
                                        skusb = skusb.replace(key + "=?,", "");
                                    }
                                }
                            }
                            Integer resultcproskuupdate = QueryEngine.getInstance().executeUpdate(skusb, proskuJson.values().toArray());
                        }
                    }
                }

            }

        }


    }
}
